import type { Router } from "vue-router";
import { checkPermission } from "./permission";
import { checkLogin } from "./login";
import { loginPath, noPermissionPath } from "@/router/config";

export const useGuard = (router: Router) => {
  router.beforeEach(async (to, _from, next) => {
    // console.warn("to", to);
    // console.warn("from", _from);

    const loginPass = await checkLogin(to);
    if (!loginPass) {
      return next({
        path: loginPath,
        query: {
          from: encodeURIComponent(to.fullPath),
        },
      });
    }

    const permissionPass = await checkPermission(to);
    if (!permissionPass) {
      return next({
        path: noPermissionPath,
        query: {
          target: encodeURIComponent(to.fullPath),
        },
      });
    }
    next();
  });

  router.beforeResolve((to) => {
    const {
      meta: { title },
    } = to;
    document.title = title;
  });
};
